const fs = require('fs')
const { isJsonByFilePath, isJsByFilePath, isCssByFilePath } = require('./index.js')
const { transFromCodeByPreset, getDepByAst } = require('./babelTools.js')
const { getCssDep } = require('./postcssTools.js')
const genCode = (code) => {
  return `function (require,module,exports) {${code}}`
}
let id = 0
const getCodeAndDepWithContent = (preCode) => {
  const { code, ast } = transFromCodeByPreset(preCode)
  const dependencies = getDepByAst(ast)
  return {
    code: genCode(code),
    dependencies,
    id: id++
  }
}
const getCodeWithJson = (jsonString) => {
  const code = `export default ${jsonString}`
  return {
    code: genCode(transFromCodeByPreset(code).code),
    dependencies: [],
    id: id++
  }
}
const getCodeWithCss = (cssString) => {
  const { css, dependencies } = getCssDep(cssString)
  const cssImport = dependencies.reduce((pre, item) => {
    pre += `require(${item});`;
    return pre
  }, '')
  const code = `
  ${cssImport}
  const style = document.createElement('style')
  style.innerHTML = ${JSON.stringify(css)}
  document.head.appendChild(style)
`
  return {
    code: genCode(transFromCodeByPreset(code).code),
    // 这里是postcss留下的bug，需要特殊处理一下
    dependencies:dependencies.map(item=>item.replace(/'/g,'')),
    id: id++
  }
}
const getCodeAndDepWithPath = (absPath) => {
  const contet = fs.readFileSync(absPath, { encoding: 'utf-8' })
  let ctx = {}
  if (isJsByFilePath(absPath)) {
    ctx = getCodeAndDepWithContent(contet)
  } else if (isJsonByFilePath(absPath)) {
    ctx = getCodeWithJson(contet)
  } else if (isCssByFilePath(absPath)) {
    ctx = getCodeWithCss(contet)
  }
  return {
    ...ctx,
    absPath,
  }
}
module.exports = {
  getCodeAndDepWithPath,
}
